<?php
declare (strict_types = 1);

namespace app\middleware\Admin;

use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtils;
use Firebase\JWT\Key;
use think\facade\Env;

class Admin
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token = $request->header('auth-key');
        var_dump($token);
        if($token){
            $res = $this->verify_token($token);
            if($res['flag'] == '1'){
                $requestData = $request->post();
                $requestData = array(
                    $requestData,
                    $res['authInfo']
                );
                $request->withPost($requestData);
                return $next($request);
            }else if($res['flag'] == '2'){
                return return_msg(0,'token过期');
            }else if($res['flag'] == '3'){
                return return_msg(0,'token校验失败');
            }
        }else{
            return return_msg(0,'token未传入');
        }
    }

    // 解码校验jwt
    public function verify_token($token)
    {
        $key = md5(Env::get('JWT.jwt_secret_key')); // jwt签发秘钥
        try {
            $keyref = JWTUtils::decode($token,new Key($key,'HS256'));
            $jwtAuth = json_encode($keyref);
            $authInfo = json_decode($jwtAuth, true);
            return array(
                "flag"=>'1',
                "authInfo"=>$authInfo
            );
        } catch (ExpiredException $e) {
            return array(
                "flag"=>'2'
            );
        } catch (\Exception $e) {
            return array(
                "flag"=>'3'
            );
        }
    }
}
